
var QWebPage = QWebControl.extend('QWebPage', {

	url : "",
	call_stack : [],
	controls_index : {},
	base_href : "",
	request_url : "",
	instance_id : null,
	_event_callback_js_data : null,
	
	MaxZIndex : 100000001,
	
	// this is the constructor
	init : function() // can add params
	{
		this._super();
		// this.viewstate = {}; viewstate to the webpage
		
		jQuery(this).bind("ev_jsParamsUpdated", function () 
			{
				var page_title = this.getJsParam("page_title");
				var page_description = this.getJsParam("page_description");
				var page_keywords = this.getJsParam("page_keywords");
				
				if (page_title)
					this.setPageTitle(page_title);
				if (page_description)
					this.setPageDescription(page_description);
				if (page_keywords)
					this.setPageKeywords(page_keywords);

				// alert(page_title);
			});
	},
	
	load : function()
	{
		// works to this point // alert('loading page');
	},
	
	_internalAfterLoad : function()
	{
		// alert("_internalAfterLoad");
		var ref_this = this;

		jQuery.history.init(function (hash) {ref_this._internalHashChanged(hash);});
		/* jQuery(window).hashchange(function() { ref_this._internalHashChanged(location.hash); });
        ref_this._internalHashChanged(location.hash); */
		
		jQuery("#___qWebAjaxLoader").css({"position" : "fixed", "padding" : "2px 6px 2px 6px",
			"border-right" : "1px solid #727218", "border-bottom" : "1px solid #727218", 
			"top" : "0px", "left" : "0", "background-color" : "#F6F6D0", "width" : "72px", "height" : "16px"});
			
		jQuery("#___qWebAjaxLoader img").css({"display" : "block", "float" : "right", "width" : "16px", "height" : "16px"});
		jQuery("#___qWebAjaxLoader div").css({"display" : "block", "float" : "left", "width" : "52px", "font-weight" : "bold", "font-size" : "11px", "line-height" : "14px"});
	},
	
	showLoadingIcon : function()
	{
		jQuery("#___qWebAjaxLoader").show();
	},
	
	hideLoadingIcon : function()
	{
		jQuery("#___qWebAjaxLoader").hide();
	},
	
	_internalHashChanged : function (hash)
	{
		var ref_this = this;
		if (hash && (hash.length > 0))
		{
			// the hash has changed, we need to trigger the events specified
			var send_vars = "";
			var send_pos = 0;
			
			for (var i = 0; i < this.call_stack.length; i++)
			{
				if (send_pos > 0)
					send_vars += "&";
				send_vars += "__qwl" + send_pos + "=" + urlencode(this.call_stack[i]);
				send_pos++;
			}
	
			send_vars += "&__qajax=1&__qid=" + urlencode(this.instance_id);
			
			this.showLoadingIcon();
			
			jQuery.ajax({
				type: "POST",
				url: this.base_href + this.request_url + "?" + send_vars,
				data: {"___q" : hash},
				dataType : "text",
				success: function (msg) {
					try
					{
						eval(msg);
						ref_this.hideLoadingIcon();
					}
					catch (ex)
					{
						var err_msg;
						if (ex.message)
							err_msg = ex.message;
						else
							err_msg = ex;
	
						GetQWebPage().setDebugText(err_msg + 
							"<br/>\n================================================================================<br/>\n" + msg, 
							true);
							
						ref_this.hideLoadingIcon();
					}
				},
				error: function (request, textStatus, errorThrown) {
                    
					// XMLHttpRequest, textStatus, errorThrown
					ref_this.hideLoadingIcon();
					
					var err = request.responseText;
					
					GetQWebPage().setDebugText(err, true);
                }
			});
			// window.location = this.base_href + this.request_url + "?___q=" + hash;
		}
		this.onHashChanged(hash);
	},
	
	setHashInBrowser : function (hash)
	{
		// set the new hash but do not trigger any event
		jQuery.history.load(hash, true);
		
		this.onHashChanged(hash);
	},
	
	onHashChanged : function (hash)
	{
		
	},
	
	setHash : function (hash)
	{
		// set the new hash and trigger events
		jQuery.history.load(hash);
	},
	
	getHash : function ()
	{
		if (window.location.hash)
			return window.location.hash.replace(/^#/, '');
		else
			return null;
	},
	
	getPageLink : function (hash)
	{
		/*
		for (var x in window.location)
			alert(x + " : " + window.location[x]);
		var hash = this.getHash();
		if (hash && (hash.length > 0))
			return window.location.href + "#" + hash;
		else
		*/
		return window.location.href;
	},
	
	copyPageLink : function (hash)
	{
		var link = this.getPageLink();
		// jQuery.copy(link);
		alert(link);
	},
	
	replaceDomElement : function(element_id, html_text, rebuild_js)
	{
		if (element_id == this.fullId)
			jQuery("body").html(html_text);
		else
			jQuery('#' + element_id).before(html_text).remove();
	},
	
	getQWebControlById : function(element_id)
	{
		// alert(this.controls_index[element_id]);
		if (this.controls_index[element_id])
			return this.controls_index[element_id];
		return null;
	},
	
	addJsDynamically : function(file, attrs, wait_on_vars)
	{
		if (wait_on_vars)
		{
			for (var x = 0; x < wait_on_vars.length; x++)
			{
				if (window[wait_on_vars[x]] === undefined)
				{
					var ref_this = this;
					setTimeout(function () {ref_this.addJsDynamically(file, attrs, wait_on_vars)}, 100);
					return;
				}
			}
		}
		
		var script = document.createElement("script");
		script.type = "text/javascript";
		// load async for other domains : script.async = true;
		script.src = file;
		document.getElementsByTagName("head")[0].appendChild(script);
	},

	addCssDynamically : function(file, attrs)
	{
		var link = document.createElement("link");
		link.type = "text/css";
		link.rel = "stylesheet";
		link.href = file;
		document.getElementsByTagName("head")[0].appendChild(link);
	},

	addResourceDynamically : function(file, type, attrs, wait_on_vars)
	{
		if (type == "js")
			this.addJsDynamically(file, attrs, wait_on_vars);
		else if (type == "css")
			this.addCssDynamically(file, attrs);
		else
			throw "Unknown resource type : " + type;
		
	},
	
	removeResourceDynamically : function(file, type)
	{
		if (type == "css")
			this.removeCssDynamically(file);
		else
			throw "Unknown resource type : " + type;
	},

	removeCssDynamically : function(file)
	{
		var head = document.getElementsByTagName("head")[0];
		var links = head.getElementsByTagName("link");

		for (var i = 0; i < links.length; i++)
		{
			var href = links[i].getAttribute("href");
			if (href == file)
			{
				links[i].parentNode.removeChild(links[i]);
			}
		}
	},
	
	setDebugText : function (text, is_error)
	{
		var elem = jQuery("#QWebApp_DEBUG_DIV__");
		var elem_txt = jQuery("#QWebApp_DEBUG_DIV_TXT");
		
		if (text)
		{
			if (is_error)
			{
				text = "<h3>Error</h3>" + text;
				// unset
				elem.css({"bottom" : "", "right" : "", "max-height" : "", "max-width" : ""});
				// now set
				elem.css({"width" : "90%", "height" : "90%", "left" : "5%", "top" : "5%", "margin" : "auto"});
					
			}
			else
			{
				// unset
				elem.css({"width" : "", "height" : "", "left" : "", "top" : "", "margin" : ""});
				// now set
				elem.css({"bottom" : "0px", "right" : "0px", "max-height" : "50%", "max-width" : "90%"});
			}

			elem_txt.html(text);
			elem.show();
		}
		else
			elem.hide();
	},
	
	isWebPage : function ()
	{
		return true;
	},
	
	manageEventCallbackJsData : function ()
	{
		if (this._event_callback_js_data)
		{
			for (var i = 0; i < this._event_callback_js_data.length; i++)
			{
				var event = this._event_callback_js_data[i];
				// id, type, params

				var element = null;
				if (!event[0])
					event[0] = this.className;
				else
					element = this.getQWebControlById(event[0]);
				if (element)
				{
					element.onAfterEvent(event[1], event[2]);
					// alert("onAfterEvent: " + event[0] + ":" + event[1] + " :: " + event[2]);
				}
				else
				{
					if (this.className == event[0])
						this.onAfterEvent(event[1], event[2]);
					else
					{
						var err_data = "";
						for (var x in event)
							err_data += x + ": " + event[x] + ";\n";
						alert("Error: manageEventCallbackJsData, Not found: \n" + err_data);
					}
				}
			}

			delete this._event_callback_js_data;
			this._event_callback_js_data = null;
		}
	},
	
	setPageTitle : function (page_title)
	{
		// jQuery("title", document.getElementsByTagName("head")[0]).html(page_title);
		document.title = page_title;
		// alert(document.title);
	},
	
	setPageDescription : function (page_description)
	{
		jQuery("meta[name=description]", document.getElementsByTagName("head")[0]).attr("content", page_description);
	},
	
	setPageKeywords : function (page_keywords)
	{
		jQuery("meta[name=keywords]", document.getElementsByTagName("head")[0]).attr("content", page_keywords);
	}
});

function addDropDownElementAsOpened(element, control)
{
	// search for duplicates
	for (var i = 0; i < window.__DropDownsList__.length; i++)
	{
		var x = window.__DropDownsList__[i];
		if (x[0] == element)
			return;
	}
	window.__DropDownsList__.push([element, control]);
}

function removeDropDownElementAsOpened(element, control)
{
	for (var i = 0; i < window.__DropDownsList__.length; i++)
	{
		var x = window.__DropDownsList__[i];
		if (x[0] == element)
		{
			window.__DropDownsList__.splice(i, 1);
			return;
		}
	}
}

jQuery(document).ready(
	function ()
	{
		if (!window["Binded_hideDropDowns__"])
		{
			/*
				we store the opened drop downs as: [{dropDownElement}, {dropDownControl}]
				the dropDownElement is the div to be searched for and
				the dropDownControl is the object to call hide on
			*/
			window["__DropDownsList__"] = [];
			
			jQuery(document.body).bind("click",
				function (e)
				{
					var sender = (typeof e.target != 'undefined') ? e.target : e.srcElement;

					var dropDownElement = null;
					var dropDownControl = null;
					
					for (var i = 0; i < window.__DropDownsList__.length; i++)
					{
						var x = window.__DropDownsList__[i];
						var parent = sender;
						var dd_Element = x[0];
						
						var found = false;
						while (parent && (!dropDownElement))
						{
							// look in the drop down list
							if (parent == dd_Element)
							{
								dropDownElement = x[0];
								dropDownControl = x[1];
								found = true;
								break;
							}

							parent = jQuery(parent).parent();
							parent = parent && (parent.length > 0) ? parent : null;
						}
						
						if (!found)
						{
							x[1].hideDropDownElement(sender);
						}
					}
					
					/*
					if (sender)
						parent_div = jQuery(sender).parents(".___fk_dropdown_div");

					if (sender && parent_div && (parent_div.length > 0))
					{
						// close all but this
						if (!ref_this)
							return;
						
						var ref_this = qControl(sender);

						var all = ref_this.jQuery(".___fk_dropdown_div");
						for (var i = 0; i < all.length; i++)
						{
							if (all[i] == parent_div[0])
							{
								// nothing
							}
							else
								ref_this.hideFkDropDownResults(jQuery(".___fk_dropdown_results", all[i]));
						}
					}
					else
					{
						// close them all 
						___hideFkDropDownResults(jQuery(".___fk_dropdown_results"));
					}
					*/
					
					// ___hideFkDropDownResults(jQuery(".___fk_dropdown_results"));
				});
			
			window["Binded_hideDropDowns__"] = 1;
		}
	});
